#import "Controller.h"
#import "gnuviewController.h"
#import "GnuView.h"


@implementation Controller

- (id) activeTerm
{
	return activeTerm;
}


- appDidInit:sender
{
	id prInfo;

	activeTerm = keyTerm = [self newGnuTerm:self];

	myConnection = [NXConnection registerRoot:self withName:"gnuplotServer"];
	[myConnection runFromAppKit];

	prInfo = [NXApp printInfo];
	[prInfo setMarginLeft:0 right:0 top:0 bottom:50];
	[prInfo setOrientation:NX_LANDSCAPE andAdjust:YES];
	[prInfo setHorizCentered:YES];
	[prInfo setVertCentered:YES];

	return self;
}

-newGnuTerm:sender
{
	id win;
	char buf[256];
	NXRect frame;

	if ([NXApp loadNibSection: "gnuview.nib" owner: self] == nil) {
		return nil;
	}

	if (win = [activeTerm window]) {
		[win getFrame: &frame];
		NX_X(&frame) += offset;
		NX_Y(&frame) -= offset;
		if ( (offset += 24.0) > 100.0) offset = 0.0;

		sprintf(buf, "gnuplot %d", ++gnuviewNum);
		[win setTitle: buf];

		[win placeWindowAndDisplay: &frame];
		[win makeKeyAndOrderFront: nil];

		return activeTerm;
	}
	return nil;
}


- setActiveTerm:(id) newTerm
{
	if (activeTerm != nil) [activeTerm deactivate:self];
	
	activeTerm = newTerm;
	
	return self;
}

- printPScodeInKey:sender
{
    [[keyTerm gnuView] printPSCode:sender];

    return self;


}

- setKeyTerm:newTerm
{	
	keyTerm = newTerm;

	[NameField setStringValue:[[keyTerm window] title]];
	[NameField selectText:self];
		
	return self;
}

- setKeyTitle:sender
{
	[[keyTerm window] setTitle:[NameField stringValue]];
	[[NameField window] performClose:self];
	return self;
}

- executePScode:(char *)PSstring
{
	if (activeTerm == nil) [self newGnuTerm:self];
	
	[[activeTerm gnuView] executePS:PSstring];

	return self;
}



@end
